﻿using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Darius.API.Application.Commands
{
    public class EmailLoginSearchHandler : IRequestHandler<EmailLoginSearchCommand, Result>
    {
        private readonly IBaseRepositorys<Emails> emailsRepository;
        private readonly ILogger<EmailLoginSearchHandler> logger;

        public EmailLoginSearchHandler(IBaseRepositorys<Emails> emailsRepository, ILogger<EmailLoginSearchHandler> logger)
        {
            this.emailsRepository = emailsRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 邮箱登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(EmailLoginSearchCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CodeEnum.search };
                var list=emailsRepository.GetAll().Where(x=>x.Email==request.Email).ToList();
                if (list.Count > 0)
                {
                    list=list.Where(x=>x.Code==request.Code).ToList();
                    if (list.Count > 0)
                    {
                        list=list.Where(x=>DateTime.Now-x.CreateTime<TimeSpan.FromSeconds(60)).ToList();
                        if (list.Count > 0)
                        {
                            result.Data = list;
                            result.Messege = "邮箱登录成功";
                            result.Code = 1;
                        }
                        else
                        {
                            result.Code = -2;
                            result.Messege = "验证码已过期，请重新获取验证码";
                        }
                    }
                    else
                    {
                        result.Code = -1;
                        result.Messege = "验证码错误";
                    }
                }
                else
                {
                    result.Code = -3;
                    result.Messege = "该邮箱没有权限登录";
                }

                logger.LogInformation(result.Messege);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "邮箱登录失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = "邮箱登录失败" };
            }
        }


    }
}
